<template>
  <div>
    <el-dialog
      title="发放抽查"
      :visible="open"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800px"
      append-to-body
      @close="cancel()"
    >
      <div @click="init">这是一个抽查</div>
      <div class="flexbet">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>接收人</span>
          </div>
          <el-input placeholder="输入关键字进行过滤" v-model="filterText">
          </el-input>
          <el-tree
            show-checkbox
            highlight-current
            class="filter-tree"
            :data="data"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            ref="tree"
            @check="handleNodeCheck"
            node-key="sid"
          >
          </el-tree>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>本次发放员工</span>
          </div>
          <el-card
            class="user-card"
            v-for="(item, index) in selectedData"
            :key="index"
          >
            <div class="flexbet">
              <div>{{ item.label }}</div>
              <i
                @click="deleteUser(item)"
                class="el-icon-delete shou"
                style="margin-top: 2px"
              ></i>
            </div>
          </el-card>
        </el-card>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: flex-end"
      >
        <el-button v-preventReClick @click="cancel">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm"
          >提 交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
export default {
  props: {
    open: Boolean,
  },
  data() {
    return {
      filterText: "",
      data: [
        {
          sid: 1,
          id: 1,
          label: "门店1",
          children: [
            {
              sid: 2,
              id: 2,
              label: "岗位2",
              children: [
                {
                  sid: "1_2_5",
                  id: 5,
                  label: "员工5",
                },
                {
                  sid: "1_2_6",
                  id: 6,
                  label: "员工6",
                },
              ],
            },
            {
              sid: 3,
              id: 3,
              label: "岗位3",
              children: [
                {
                  sid: "1_3_5",
                  id: 5,
                  label: "员工5",
                },
                {
                  sid: "1_3_8",
                  id: 8,
                  label: "员工8",
                },
              ],
            },
          ],
        },
        {
          sid: 12,
          id: 12,
          label: "门店12",
          children: [
            {
              sid: 2,
              id: 2,
              label: "岗位2",
              children: [
                {
                  sid: "12_2_5",
                  id: 5,
                  label: "员工5",
                },
                {
                  sid: "12_2_6",
                  id: 6,
                  label: "员工6",
                },
              ],
            },
            {
              sid: 13,
              id: 13,
              label: "岗位13",
              children: [
                {
                  sid: "12_3_15",
                  id: 15,
                  label: "员工15",
                },
                {
                  sid: "12_3_18",
                  id: 18,
                  label: "员工18",
                },
              ],
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      //禁用的数据
      disabled_selectedData: [
        // {
        //   sid: "1_2_5",
        //   id: 5,
        //   label: "员工5",
        // },
      ],
      //选中的原始数据
      selectedData: [],
    };
  },
  watch: {
    open(e) {},
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    init() {
      // 初始化获取勾选的数据 判断父级是否可以勾选
      this.disableNodesByIds(
        this.data,
        this.disabled_selectedData.map((item) => {
          return item.id;
        })
      );
      console.log(this.data);
    },
    /* 递归地在树形结构中查找并禁用匹配的节点 */
    disableNodesByIds(tree, idsToDisable) {
      for (let node of tree) {
        if (idsToDisable.includes(node.id)) {
          this.$set(node, "disabled", true);
          this.$refs.tree.setChecked(node.sid, true);
        }
        if (node.children) {
          this.disableNodesByIds(node.children, idsToDisable); // 递归调用以处理子节点
        }
      }
    },
    /* 删除用户 */
    deleteUser(item) {
      this.handleNodeCheck(item);
    },
    /* 递归  根据searchIds中含id  选中符合条件的所有最子节点 */
    checkSameIds(data, searchIds, result = [], nodeExists) {
      for (const node of data) {
        if (node.children) {
          this.checkSameIds(node.children, searchIds, result, nodeExists);
        } else {
          console.log(node.id, searchIds, nodeExists);
          if (searchIds.includes(node.id)) {
            console.log(node.sid);
            // 排除禁用节点
            if (!node.disabled) {
              this.$refs.tree.setChecked(node.sid, nodeExists);
              result.push(node);
            }
          }
        }
      }
      return result;
    },

    /* 递归函数，用于获取某个节点的所 有最子节点 */
    getAllLeafNodes(node, result = []) {
      if (node.children) {
        node.children.forEach((child) => {
          this.getAllLeafNodes(child, result);
        });
      } else {
        // 排除禁用节点
        if (!node.disabled) {
          result.push(node.id);
        }
      }
      return result;
    },
    /* 检查 某数组(比如[5,6,7])里是否含有[5,6] */
    // const mainArray = [5, 6, 7];
    // const subArray = [5, 6];
    isSubArrayIncluded(mainArray, subArray) {
      return mainArray.some((item, index) =>
        mainArray
          .slice(index, index + subArray.length)
          .every((value, subIndex) => value === subArray[subIndex])
      );
    },
    /* 节点点击 */
    handleNodeCheck(checkedNode) {
      console.log("节点点击", checkedNode);

      //如果选中的不是员工
      if (checkedNode.children) {
        // 递归函数，用于获取某个节点的所有最子节点
        const AllLeafNodes = this.getAllLeafNodes(checkedNode);
        console.log("用于获取某个节点的所有最子节点", AllLeafNodes);
        // 判断 所有最子节点 是否在 selectedData 中存在
        const nodeExists = this.isSubArrayIncluded(
          this.selectedData.map((item) => {
            return item.id;
          }),
          AllLeafNodes
        );
        console.log("所有最子节点是否存在", nodeExists);
        this.checkSameIds(this.data, AllLeafNodes, [], !nodeExists);
      }
      //如果选中的是员工
      else {
        // 判断 checkedNode 是否在 selectedData 中存在
        const nodeExists = this.selectedData.some(
          (node) => node.id === checkedNode.id
        );
        console.log("节点是否存在", nodeExists);
        // 如果不存在则选中他 存在则禁用他 选中id相同的并勾选他
        this.checkSameIds(this.data, [checkedNode.id], [], !nodeExists);
      }
      // 在这里获取勾选的数据
      this.$nextTick(() => {
        this.selectedData = this.filterNodesBySidFormat(
          this.$refs.tree.getCheckedNodes(),
          "_"
        );
      });
    },
    /* 过滤具有特定 sid 格式的节点，并进行 id 去重 */
    filterNodesBySidFormat(data, format) {
      const filteredNodes = data.filter((node) => {
        return node.sid && (node.sid + "").includes(format) && !node.disabled;
      });

      const idMap = new Map();
      const deduplicatedNodes = filteredNodes.reduce((acc, node) => {
        if (!idMap.has(node.id)) {
          idMap.set(node.id, true);
          acc.push(node);
        }
        return acc;
      }, []);

      return deduplicatedNodes;
    },

    //   过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 提交按钮 */
    submitForm: function () {},
    // 表单重置
    reset() {},
    cancel() {
      this.$emit("update:open", false);
      this.reset();
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .user-card .el-card__body {
  padding: 10px;
}
.box-card {
  width: 350px;
}
</style>
  